<template>
  <div class="app-container">
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <div>
          <!-- 搜索表单 -->
          <el-form :model="completionQuery" :inline="true" label-width="auto">
            <div class="form-row">
              <el-form-item label="项目名称">
                <el-input
                  v-model="completionQuery.PName"
                  style="width: 177px"
                  clearable
                  placeholder="请输入项目名称"
                />
              </el-form-item>
              <el-form-item label="客户单位">
                <el-input
                  v-model="completionQuery.customer"
                  style="width: 177px"
                  clearable
                  placeholder="请输入客户单位"
                />

                <!-- <el-select
                  @change="handleCustomerChange"
                  clearable
                  v-model="completionQuery.customer"
                  placeholder="请选择客户单位"
                  style="width: 177px"
                >
                  <el-option
                    :label="item.name"
                    :value="item.name"
                    v-for="item in customerUnits"
                    :key="item.id"
                  ></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="合同编号">
                <el-input
                  v-model="completionQuery.no"
                  style="width: 177px"
                  clearable
                  placeholder="请输入合同编号"
                />
              </el-form-item>
              <el-form-item label="合同金额">
                <el-input
                  v-model="completionQuery.money"
                  style="width: 177px"
                  clearable
                  placeholder="请输入合同金额"
                />
              </el-form-item>
              <el-form-item label="项目内容">
                <el-input
                  v-model="completionQuery.content"
                  style="width: 177px"
                  clearable
                  placeholder="请输入项目内容"
                />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="立项时间">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 260px"
                  @change="handleDateChange"
                />
              </el-form-item>
              <el-form-item label="项目负责人">
                <el-input
                  v-model="completionQuery.salesman"
                  style="width: 177px"
                  clearable
                  placeholder="请输入负责人姓名"
                />
              </el-form-item>
              <el-form-item label="项目状态">
                <el-select
                  v-model="completionQuery.status"
                  style="width: 177px"
                  clearable
                  placeholder="请选择项目状态"
                  @change="handleStatusChange"
                >
                  <el-option
                    v-for="item in projectStatus"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="handleQuery"
                >搜索</el-button>
                <el-button
                  icon="el-icon-refresh"
                  @click="resetQuery"
                >重置</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-card>
    </el-collapse-transition>
    <el-card>
      <!-- 顶部操作按钮 -->
      <div class="operation-container">
        <el-button
          type="primary"
          size="small"
          class="filter-trigger"
          @click="isFilterVisible = !isFilterVisible"
        >{{ isFilterVisible ? "收起" : "检索" }}
          <i
            :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
          />
        </el-button>
        <el-button
          v-if="isAdministrators"
          type="warning"
          icon="el-icon-edit"
          size="small"
          @click="handleEditSelected"
        >修改</el-button>
        <el-button
          v-if="isAdministrators"
          type="danger"
          icon="el-icon-delete"
          size="small"
          @click="handleDeleteSelected"
        >批量删除</el-button>
        <!-- <el-button type="primary" icon="el-icon-printer" size="small"
          >预览/打印</el-button
        > -->
        <div style="float: right">
          <el-dropdown @command="handleExportExcel">
            <el-button
              type="primary"
              size="small"
            >导入/导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>excel导出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        class="main-table"
        :data="completionList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="no"
          label="合同编号"
          width="120"
          align="center"
        />
        <el-table-column
          min-width="200"
          prop="pname"
          label="项目名称"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="customer"
          label="客户单位"
          min-width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="customerType"
          label="客户类型"
          width="100"
          align="center"
        />
        <el-table-column
          prop="money"
          label="合同金额"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.money || "0" }}
          </template>
        </el-table-column>
        <el-table-column prop="salesman" label="项目负责人" width="100" />
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          width="180"
        >
          <template slot-scope="scope">
            {{ formatCreateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="status"
          label="项目状态"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getProjectStatusType(scope.row.status, scope.row.prStatus)"
            >{{
              getProjectStatus(scope.row.status, scope.row.prStatus)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleView(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin-top: 20px" type="flex" justify="end">
        <el-pagination
          background
          :current-page="completionQuery.page"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="completionQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <!-- 修改弹框 -->
    <el-dialog
      title="结案填报内容修改"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        label-width="140px"
        :rules="rules"
      >
        <el-form-item label="项目金额">
          <span class="amount">{{ editForm.money || "0" }}元</span>
        </el-form-item>

        <el-form-item label="项目税金" prop="tax">
          <el-input v-model.number="editForm.tax" placeholder="请输入项目税金">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="项目成本" prop="cost">
          <el-input v-model.number="editForm.cost" placeholder="请输入项目成本">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="项目收入" prop="income">
          <el-input
            v-model.number="editForm.income"
            placeholder="请输入项目收入"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="项目管理奖" prop="manageMoney">
          <el-input
            v-model.number="editForm.manageMoney"
            placeholder="请输入项目管理奖"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <!-- <el-form-item label="考核金额" prop="kpMoney">
          <el-input
            v-model.number="editForm.kpMoney"
            placeholder="请输入考核金额"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item> -->

        <el-form-item label="管理比例" prop="manageRate">
          <el-input
            v-model.number="editForm.manageRate"
            placeholder="请输入管理比例"
          >
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情弹框 -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      width="87%"
      title="查看详情"
      custom-class="full-height-dialog"
    >
      <div id="printArea" class="dialog-content-wrapper">
        <div class="collapse-header">
          <h3>北仑区传媒中心经营项目立项</h3>
          <!-- <span class="view-btn">点击查看</span> -->
        </div>
        <el-card>
          <div>
            <div class="detail-content">
              <div class="contract-no">合同编号：{{ projectDetail.no }}</div>
              <el-form label-width="100px" class="detail-form">
                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目名称">
                      <el-input
                        v-model="projectDetail.pname"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目采购方式">
                      <el-input
                        v-model="projectDetail.projectFrom"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="客户类型">
                      <el-input
                        v-model="projectDetail.customerType"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="客户单位">
                      <el-input
                        v-model="projectDetail.customer"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目领域">
                      <el-input
                        v-model="projectDetail.projectArea"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <!-- <el-form-item label="是否重点客户">
                      <el-input
                        v-model="projectDetail.isImportant"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item> -->
                    <el-form-item label="项目负责人">
                      <el-input
                        v-model="projectDetail.salesman"
                        style="width: 100%"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="存量类型">
                      <el-input
                        v-model="projectDetail.stockType"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="执行时间">
                      <el-input
                        v-model="projectDetail.duration"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="合同金额">
                      <el-input
                        v-model="projectDetail.money"
                        disabled
                        style="width: 100%"
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="是否到账">
                      <el-input
                        v-model="projectDetail.isAccount"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="划转对象实际金额" label-width="125px">
                      <el-input
                        v-model="projectDetail.taxInclusivePrice"
                        style="width: 100%"
                        disabled
                      >
                        <template slot="append">元</template>
                        ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <!-- <el-form-item label="是否立项">
                      <el-input
                        v-model="projectDetail.mpSuggest"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item> -->
                    <el-form-item label="实际收入">
                      <el-input
                        v-model="projectDetail.income"
                        style="width: 100%"
                        disabled
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="到账金额">
                      <el-input
                        v-model="projectDetail.receiveMoney"
                        disabled
                        style="width: 100%"
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目奖励">
                      <el-input
                        v-model="projectDetail.manageRate"
                        disabled
                        style="width: 100%"
                      >
                        <template slot="append">%</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="24">
                    <el-form-item label="内容及要求">
                      <el-input
                        v-model="projectDetail.content"
                        type="textarea"
                        :rows="4"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </el-card>

        <el-card style="margin-top: 20px">
          <div>
            <div class="project-type">
              <div class="type-title">项目类型</div>
              <el-table
                class="project-type-table"
                :header-cell-style="{ background: '#f5f7fa' }"
                :data="projectDetail.list || []"
                border
                style="width: 100%"
                :span-method="objectSpanMethod"
              >
                <el-table-column
                  prop="platform"
                  label="平台产品IP"
                  width="150"
                  align="center"
                />
                <el-table-column
                  prop="department"
                  label="执行事业部"
                  width="200"
                  align="center"
                />
                <el-table-column
                  prop="content"
                  label="执行内容及要求"
                  min-width="300"
                  align="center"
                />
                <el-table-column
                  prop="attribute"
                  label="属性"
                  width="150"
                  align="center"
                />
                <el-table-column
                  prop="money"
                  label="金额"
                  width="120"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ scope.row.money || "0" }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="estimatedCost"
                  label="成本"
                  width="120"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ scope.row.estimatedCost || "0" }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="transferCompany"
                  label="划转对象"
                  width="150"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ scope.row.transferCompany || "无" }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="transferMoney"
                  label="划转金额"
                  width="150"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ scope.row.transferMoney || "0" }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>

        <el-card style="margin-top: 20px">
          <div style="border: 2px solid #ebeef5">
            <div class="contract-info">
              <div class="info-item">
                <div class="info-label">合同电子版</div>
                <div class="info-content">
                  <a
                    v-if="projectDetail.contractFile"
                    :href="projectDetail.contractFile"
                    class="download-link"
                    @click.prevent="
                      handleFileDownload(projectDetail.contractFile)
                    "
                  >
                    {{ getFileName(projectDetail.contractFile) }}(点击下载文件)
                  </a>
                  <div class="button-group">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleFileDownload(projectDetail.contractFile)"
                    >下载</el-button>
                    <el-button
                      size="small"
                      @click="handlePreview"
                    >预览</el-button>
                  </div>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">负责人备注</div>
                <div class="info-content">
                  {{ projectDetail.remarks || "" }}
                </div>
              </div>

              <div class="info-section">
                <div style="border: 1px solid #ccc">
                  <div class="info-row">
                    <div class="info-col">
                      <div
                        class="info-label"
                        style="width: 180px; color: black; font-weight: bold"
                      >
                        项目立项意见
                      </div>
                      <div class="info-content">
                        {{
                          projectDetail.lsuggest
                            ? `${projectDetail.luser}：${
                              projectDetail.lsuggest || ""
                            }`
                            : ""
                        }}
                      </div>
                    </div>
                    <!-- <div class="info-col">
                      <div class="info-label">项目立项人</div>
                      <div class="info-content">
                        {{ projectDetail.luser || "" }}
                      </div>
                    </div> -->
                  </div>
                </div>

                <div style="border: 1px solid #ccc">
                  <div class="info-row full-width">
                    <div class="info-label">完成概述</div>
                    <div class="info-content">
                      {{ projectDetail.describe || "" }}
                    </div>
                  </div>

                  <div class="info-row">
                    <div class="info-col">
                      <div class="info-label">结案人</div>
                      <div class="info-content">
                        {{ projectDetail.createName || projectDetail.salesman }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">结案时间</div>
                      <div class="info-content">
                        {{
                          formatCreateTime(projectDetail.endCreateTime) || ""
                        }}
                      </div>
                    </div>
                  </div>
                </div>

                <div style="border: 1px solid #ccc">
                  <div class="info-row full-width">
                    <div class="info-col">
                      <div class="info-label">融合发展事业部意见</div>
                      <div class="info-content">
                        {{
                          projectDetail.rmSuggest
                            ? `${projectDetail.rmUserName}：${
                              projectDetail.rmSuggest || ""
                            }`
                            : ""
                        }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">审批时间</div>
                      <div class="info-content">
                        {{ formatCreateTime(projectDetail.rmUserTime) || "" }}
                      </div>
                    </div>
                  </div>

                  <!-- <div class="info-row">
                    <div class="info-col">
                      <div class="info-label">审批人</div>
                      <div class="info-content">
                        {{ projectDetail.rmUserName || "" }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">审批时间</div>
                      <div class="info-content">
                        {{ formatCreateTime(projectDetail.rmUserTime) || "" }}
                      </div>
                    </div>
                  </div> -->
                </div>

                <div style="border: 1px solid #ccc">
                  <div class="info-row three-cols">
                    <div class="info-col">
                      <div class="info-label">项目成本</div>
                      <div class="info-content">
                        {{ projectDetail.cost || "0" }}元
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">项目税金</div>
                      <div class="info-content">
                        {{ projectDetail.tax || "0" }}元
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">项目收入</div>
                      <div class="info-content">
                        {{ projectDetail.income || "0" }}元
                      </div>
                    </div>
                  </div>

                  <div class="info-row">
                    <div class="info-col">
                      <div class="info-label">项目奖励</div>
                      <div class="info-content">
                        {{ projectDetail.manageMoney || "0" }}元
                      </div>
                    </div>
                    <!-- <div class="info-col">
                    <div class="info-label">融合发展事业部意见</div>
                    <div class="info-content">{{ projectDetail.rmSuggest || "" }}</div>
                  </div> -->
                  </div>
                </div>

                <div style="border: 1px solid #ccc">
                  <div class="info-row full-width">
                    <div class="info-col">
                      <div class="info-label">运营中心意见</div>
                      <div class="info-content">
                        {{
                          projectDetail.rcenterSuggest
                            ? `${projectDetail.rcenterUserName}：${
                              projectDetail.rcenterSuggest || ""
                            }`
                            : ""
                        }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">审批时间</div>
                      <div class="info-content">
                        {{
                          formatCreateTime(projectDetail.rcenterUserTime) || ""
                        }}
                      </div>
                    </div>
                  </div>

                  <!-- <div class="info-row">
                    <div class="info-col">
                      <div class="info-label">审批人</div>
                      <div class="info-content">
                        {{ projectDetail.rcenterUserName || "" }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">审批时间</div>
                      <div class="info-content">
                        {{
                          formatCreateTime(projectDetail.rcenterUserTime) || ""
                        }}
                      </div>
                    </div>
                  </div> -->
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <!-- 时间线部分 -->
      <el-card style="margin-top: 20px">
        <div>
          <div class="timeline-section">
            <el-timeline>
              <!-- 结案初审 -->
              <el-timeline-item
                v-if="projectDetail.prStatus >= 3"
                :timestamp="formatCreateTime(projectDetail.rmUserTime)"
                placement="top"
                type="primary"
              >
                <el-card>
                  <h4>已通过结案初审</h4>
                  <p>操作人：{{ projectDetail.rmUserName }}</p>
                </el-card>
              </el-timeline-item>

              <!-- 计财部填报 -->
              <el-timeline-item
                v-if="projectDetail.prStatus >= 4"
                :timestamp="formatCreateTime(projectDetail.financeUserTime)"
                placement="top"
                type="primary"
              >
                <el-card>
                  <h4>计财部填报</h4>
                  <p>操作人：{{ projectDetail.financeUserName }}</p>
                </el-card>
              </el-timeline-item>

              <!-- 运营中心审批 -->
              <el-timeline-item
                v-if="projectDetail.prStatus === 6"
                :timestamp="formatCreateTime(projectDetail.rCenterUserTime)"
                placement="top"
                type="primary"
              >
                <el-card>
                  <h4>运营中心已审批</h4>
                  <p>操作人：{{ projectDetail.rcenterUserName }}</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button v-print="printObj" type="primary">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selEndCaseListApi,
  updateEndCaseByIdApi,
  delEndCaseByIdsApi,
  selEndCaseByIdApi
} from '@/api/project-management'
import { filePreviewApi, selFileUrlApi } from '@/api/uploadFile'
import { selCustomerUnitListApi } from '@/api/basic-data'
import { mapGetters } from 'vuex'
// import Print from "vue-print-nb";
// import Print from "@/print";
export default {
  name: 'ProjectInput',
  // directives: {
  //   print: Print,
  // },
  data() {
    return {
      tableData: [
        {
          id: 1,
          contractNo: '202502051',
          projectName: '宁波市北仑区妇女联合会年度合作协议（妇联）',
          customerUnit: '宁波市北仑区妇女联合会',
          contractAmount: 48000,
          projectManager: '周永声',
          createTime: '2025-02-05 10:56',
          status: '已通过'
        },
        {
          id: 2,
          contractNo: '202501221',
          projectName: '青田年统留守儿童北仑研学活动策划合作协议',
          customerUnit: '宁波北仑圆满旅行社有限责任公司',
          contractAmount: 4000,
          projectManager: '张佳丽',
          createTime: '2025-01-22 00:00',
          status: '已通过'
        },
        {
          id: 3,
          contractNo: '202501202',
          projectName: '教育局少儿春晚合作协议',
          customerUnit: '宁波市北仑区教育局',
          contractAmount: 30000,
          projectManager: '张佳丽',
          createTime: '2025-01-20 14:23',
          status: '已通过'
        },
        {
          id: 4,
          contractNo: '202501172',
          projectName: '白峰街道90、00多村共富记视频策划合作协议',
          customerUnit: '宁波市北仑区人民政府白峰街道办事处',
          contractAmount: 20000,
          projectManager: '郑颖超',
          createTime: '2025-01-17 19:53',
          status: '已通过'
        },
        {
          id: 5,
          contractNo: '202501162',
          projectName: '白峰街道年终节目一起向春天合作协议',
          customerUnit: '宁波市北仑区人民政府白峰街道办事处',
          contractAmount: 149000,
          projectManager: '郑颖超',
          createTime: '2025-01-16 00:00',
          status: '已通过'
        },
        {
          id: 6,
          contractNo: '202501161',
          projectName: '测试项目(勿审/勿删)',
          customerUnit: '测试部门',
          contractAmount: 1,
          projectManager: '周洪涛',
          createTime: '2025-01-16 16:22',
          status: '已通过'
        },
        {
          id: 7,
          contractNo: '202501151',
          projectName: '"情系万家"暖冬行动启动仪式',
          customerUnit: '宁波市北仑区慈善总会',
          contractAmount: 23450,
          projectManager: '吕泽婷',
          createTime: '2025-01-15 00:00',
          status: '已通过'
        },
        {
          id: 8,
          contractNo: '202501091',
          projectName: '测试项目',
          customerUnit: '北仑区传媒中心',
          contractAmount: 0,
          projectManager: '刘岩',
          createTime: '2025-01-09 08:59',
          status: '已通过'
        },
        {
          id: 9,
          contractNo: '202501062',
          projectName: '宁波儿童公园亲子欢乐跑活动',
          customerUnit: '宁波市宝韵艺术培训中心',
          contractAmount: 49000,
          projectManager: '曹跃',
          createTime: '2025-01-06 00:00',
          status: '已通过'
        },
        {
          id: 10,
          contractNo: '202501061',
          projectName: '北仑电厂项目宣传视频',
          customerUnit: '浙江德塔壳特数据技术有限公司',
          contractAmount: 20000,
          projectManager: '吕泽婷',
          createTime: '2025-01-06 00:00',
          status: '已通过'
        }
      ],
      // 结案查询参数
      completionQuery: {
        page: 1,
        pageSize: 10,
        content: '', // 项目内容
        customer: '', // 客户
        dt1: '', // 立项时间
        dt2: '', // 立项时间
        money: '', // 合同金额
        no: '', // 合同编号
        PName: '', // 项目名称
        salesman: '', // 项目负责人
        status: 0 // 项目状态
      },
      completionList: [], // 结案列表
      loading: false, // 加载
      isFilterVisible: false,
      total: 0, // 总条数
      dialogVisible: false,
      detailDialogVisible: false,
      selectedRow: null,
      // 修改
      editForm: {
        id: '', // ID
        eid: '', // ID
        money: '', // 金额
        tax: '', // 税额
        cost: '', // 成本费用
        income: '', // 收入金额
        // kpMoney: "", // 考核金额
        manageMoney: '', // 管理金额
        manageRate: '' // 管理比例
      },
      projectDetail: {}, // 项目详情
      id: '', // 选中行的id
      // 项目状态列表
      projectStatus: [
        { label: '全部', value: 0 },
        { label: '已驳回', value: -1 },
        { label: '待结案', value: 1 },
        { label: '待评审', value: 2 },
        { label: '已结案', value: 3 }
      ],
      rules: {
        tax: [
          { required: true, message: '请输入项目税金', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        cost: [
          { required: true, message: '请输入项目成本', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        income: [
          { required: true, message: '请输入项目收入', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        // kpMoney: [
        //   { required: true, message: "请输入考核金额", trigger: "blur" },
        //   { type: "number", message: "请输入数字", trigger: "blur" },
        // ],
        manageMoney: [
          { required: true, message: '请输入管理金额', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        manageRate: [
          { required: true, message: '请输入管理比例', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ]
      },
      customerUnits: [], // 客户单位列表
      selectedIds: [], // 选中的id
      dateRange: [], // 日期范围
      type: 'endCase', // 导出类型
      // 客户类型列表参数
      selCustomerTypeListQuery: {
        page: 1,
        pageSize: 99,
        name: ''
      },
      printObj: {
        id: 'printArea',
        popTitle: '结案查询详情',
        preview: false,
        extraCss: '',
        beforeEntryIframe() {
          try {
            // 获取打印区域
            const printArea = document.getElementById('printArea')
            if (!printArea) return

            // 添加边框样式
            const styleElement = document.createElement('style')
            styleElement.id = 'print-style-temp'
            styleElement.textContent = `
              /* 整个表格添加边框 */
              #printArea .el-table {
                border: 1px solid #dcdfe6 !important;
                border-collapse: collapse !important;
              }
              
              /* 确保所有单元格都有边框 */
              #printArea .el-table th.el-table__cell,
              #printArea .el-table td.el-table__cell {
                border: 1px solid #dcdfe6 !important;
              }
              
              /* 确保表头背景色 */
              #printArea .el-table th.el-table__cell {
                background-color: #f5f7fa !important;
              }
              
              /* 移除干扰元素 */
              #printArea .el-table::before,
              #printArea .el-table::after {
                display: none !important;
              }
            `
            document.head.appendChild(styleElement)

            // 处理表格宽度和列组
            const tableNode = printArea.querySelectorAll(
              '.el-table__header,.el-table__body'
            )
            tableNode.forEach((tableItem) => {
              tableItem.style.width = '100%'
              tableItem.style.borderCollapse = 'collapse'

              // 设置表格列宽比例
              const colgroup = tableItem.querySelector('colgroup')
              if (colgroup) {
                colgroup.innerHTML = ''

                const widths = [
                  '11.2%', // 150px -> 11.2%
                  '14.9%', // 200px -> 14.9%
                  '22.4%', // 300px -> 22.4%
                  '11.2%', // 150px -> 11.2%
                  '8.9%', // 120px -> 8.9%
                  '8.9%', // 120px -> 8.9%
                  '11.2%', // 150px -> 11.2%
                  '11.2%' // 150px -> 11.2%
                ]

                widths.forEach((width) => {
                  const col = document.createElement('col')
                  col.style.width = width
                  colgroup.appendChild(col)
                })
              }
            })

            // 直接为所有表格和单元格添加边框
            const tables = printArea.querySelectorAll('.el-table')
            tables.forEach((table) => {
              table.style.border = '1px solid #dcdfe6'
              table.style.borderCollapse = 'collapse'

              // 处理所有单元格
              const cells = table.querySelectorAll(
                'th.el-table__cell, td.el-table__cell'
              )
              cells.forEach((cell) => {
                cell.style.border = '1px solid #dcdfe6'
              })

              // 表头单元格额外处理
              const headerCells = table.querySelectorAll('th.el-table__cell')
              headerCells.forEach((cell) => {
                cell.style.backgroundColor = '#f5f7fa'
              })
            })
          } catch (error) {
            console.error('Error in beforeEntryIframe:', error)
          }
        },
        closeCallback(vue) {
          console.log('关闭了打印工具')
          // 移除临时样式
          const tempStyle = document.getElementById('print-style-temp')
          if (tempStyle) {
            tempStyle.parentNode.removeChild(tempStyle)
          }
        }
      }
    }
  },
  created() {
    this.selEndCaseList() // 获取项目列表
    this.selCustomerUnitList() // 获取客户单位列表
  },
  computed: {
    ...mapGetters(['isAdministrators'])
  },
  methods: {
    // 处理日期变化
    handleDateChange(val) {
      if (val) {
        console.log(val)
        // 格式化日期函数
        const formatDate = (date) => {
          const d = new Date(date)
          const year = d.getFullYear()
          const month = String(d.getMonth() + 1).padStart(2, '0')
          const day = String(d.getDate()).padStart(2, '0')
          return `${year}-${month}-${day}`
        }

        this.completionQuery.dt1 = formatDate(val[0])
        this.completionQuery.dt2 = formatDate(val[1])
      } else {
        this.completionQuery.dt1 = ''
        this.completionQuery.dt2 = ''
      }
      this.selEndCaseList()
    },
    // 批量删除
    async handleDeleteSelected() {
      console.log('批量删除')
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要删除的结案')
        return
      }
      this.$confirm('此操作将永久删除该结案, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await delEndCaseByIdsApi(this.selectedIds)
          console.log(res)
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.selEndCaseList()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        })
        .catch(() => {})
    },
    // 导出excel
    async handleExportExcel() {
      console.log('导出excel')
      let loading = null
      try {
        await this.$confirm(
          '此操作将导出所有项目及评审信息, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        // 显示loading
        loading = this.$loading({
          lock: true,
          text: '正在导出数据,请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        const res = await filePreviewApi(this.type)
        console.log(res)
        if (res.code === 1 && res.data) {
          // 创建a标签下载
          const link = document.createElement('a')
          link.href = res.data
          link.download = '项目结案信息导出.xlsx'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          this.$message.success('导出成功')
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        // console.error("导出错误:", error);
        // this.$message.error("导出失败");
      } finally {
        // 关闭loading
        if (loading) {
          loading.close()
        }
      }
    },
    // 客户单位列表查询
    async selCustomerUnitList() {
      const res = await selCustomerUnitListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.customerUnits = res.records
    },
    // 查询项目结案列表
    async selEndCaseList() {
      this.loading = true
      try {
        const res = await selEndCaseListApi(this.completionQuery)
        console.log(res)
        this.completionList = res.records
        this.total = res.total
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    // 结案查询
    handleQuery() {
      this.completionQuery.page = 1
      this.selEndCaseList()
    },
    // 重置
    resetQuery() {
      this.completionQuery = {
        PName: '',
        customer: '',
        no: '',
        money: '',
        content: '',
        dt1: '',
        salesman: '',
        status: 0
      }
    },
    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 项目状态改变
    handleStatusChange(val) {
      console.log(val)
      if (val === '') {
        this.completionQuery.status = 0
      }
      this.selEndCaseList()
    },
    // 分页
    handleSizeChange(pageSize) {
      this.completionQuery.pageSize = pageSize
      this.selEndCaseList()
    },
    // 当前页
    handleCurrentChange(page) {
      this.completionQuery.page = page
      this.selEndCaseList()
    },
    handleView(row) {
      console.log('查看详情', row)
      this.detailDialogVisible = true
      this.projectDetail = row
      console.log(this.projectDetail)
    },
    // 表格选择行变化
    handleSelectionChange(selection) {
      this.selectedRow = selection.length ? selection[0] : null
      this.selectedIds = selection.map((item) => item.id)
      console.log(selection)
      this.id = selection[0].id
    },
    // 点击修改按钮
    async handleEditSelected() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要修改的结案')
        return
      }
      if (this.selectedIds.length > 1) {
        this.$message.warning('请选择单行结案')
        return
      }

      // this.handleEdit(this.selectedRow);
      const res = await selEndCaseByIdApi(this.id)
      console.log(res)
      if (res.code === 1) {
        this.editForm = res.data
        this.dialogVisible = true
      } else {
        this.$message.error(res.msg || '获取结案失败')
      }
      // this.handleEdit(res.data);
    },
    // 封装获取项目状态
    getProjectStatus(status, prStatus) {
      if (status === null || status === undefined) return ''
      const statusNum = Number(status)
      const prStatusNum = Number(prStatus)
      if ((statusNum === 5 || statusNum === 6) && prStatusNum === 6) {
        return '已结案'
      } else if (prStatusNum > 1 && prStatusNum <= 5) {
        return '待评审'
      } else if (prStatusNum === 1) {
        return '待结案'
      } else if (prStatusNum === -1) {
        return '已驳回'
      }
      return ''
    },
    // 封装获取项目状态类型
    getProjectStatusType(status, prStatus) {
      if (status === null || status === undefined) return ''
      const statusNum = Number(status)
      const prStatusNum = Number(prStatus)
      if ((statusNum === 5 || statusNum === 6) && prStatusNum === 6) {
        return 'success'
      } else if (prStatusNum > 1 && prStatusNum <= 5) {
        return 'warning'
      } else if (prStatusNum === 1) {
        return 'warning'
      } else if (prStatusNum === -1) {
        return 'danger'
      }
      return 'info'
    },
    // 获取文件名
    getFileName(url) {
      if (!url) return ''
      // 截取_后面的部分作为文件名
      console.log(url.split('_').pop())
      return url.split('_').pop()
    },
    // 处理文件预览
    async handlePreview() {
      if (!this.projectDetail.contractFile) {
        this.$message.warning('文件链接不存在')
        return
      }
      try {
        // 获取预览链接
        const res = await selFileUrlApi(this.projectDetail.contractFile)
        console.log(res)
        if (res.code === 1 && res.data) {
          // 在新窗口中打开预览链接
          window.open(res.data, '_blank')
        } else {
          在
          this.$message.error(res.msg || '获取预览链接失败')
        }
      } catch (error) {
        console.error('预览失败:', error)
        this.$message.error('预览失败，请重试')
      }
    },
    // 处理文件下载
    handleFileDownload(url) {
      if (!url) {
        this.$message.warning('文件链接不存在')
        return
      }

      // 拼接完整的下载地址
      const baseUrl = 'http://192.168.11.2:8081'
      const fullUrl = `${baseUrl}${url}`

      // 获取文件名 - 截取_后面的部分
      const fileName = url.split('_').pop()
      console.log(fullUrl)

      try {
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', fileName) // 使用新的文件名
        document.body.appendChild(link)

        link.click()

        document.body.removeChild(link)
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败，请重试')
      }
    },
    // 打开修改弹框
    handleEdit(row) {
      this.dialogVisible = true
      this.editForm = {
        id: row.id, // ID
        eid: row.eid, // ID
        money: row.money || '0', // 金额
        tax: row.tax || '', // 税额
        cost: row.cost || '', // 成本费用
        income: row.income || '', // 收入金额
        // kpMoney: row.kpMoney || "", // 考核金额
        manageMoney: row.manageMoney || '', // 管理金额
        manageRate: row.manageRate || '' // 管理比例
      }
    },

    // 提交修改
    handleSubmit() {
      this.$refs.editForm.validate(async(valid) => {
        if (valid) {
          try {
            // const params = {
            //   dto: {
            //     ...this.editForm,
            //     // 确保所有数值类型字段都是数字
            //     tax: Number(this.editForm.tax),
            //     // cost: Number(this.editForm.cost),
            //     // income: Number(this.editForm.income),
            //     // kpMoney: Number(this.editForm.kpMoney),
            //     // manageMoney: Number(this.editForm.manageMoney),
            //     // manageRate: Number(this.editForm.manageRate),
            //   },
            // };
            delete this.editForm.kpMoney // 删除考核金额
            const res = await updateEndCaseByIdApi(this.editForm)
            // const res = await updateEndCaseApi(params)
            // if (res.code === 200) {
            if (res.code === 1) {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.selEndCaseList() // 刷新列表
            } else {
              this.$message.error('修改失败，请重试')
            }
            // }
          } catch (error) {
            console.error('修改失败:', error)
            this.$message.error('修改失败，请重试')
          }
        }
      })
    },

    // 弹框关闭后的回调
    handleDialogClosed() {
      this.$refs.editForm.resetFields()
      this.editForm = {
        id: '', // ID
        eid: '', // EID
        money: '', // 金额
        tax: '', // 税额
        cost: '', // 成本费用
        income: '', // 收入金额
        // kpMoney: "", // 考核金额
        manageMoney: '', // 管理金额
        manageRate: '' // 管理比例
      }
    },
    // 客户单位改变
    handleCustomerChange(val) {
      console.log(val)
      this.selEndCaseList()
    },
    // 添加表格合并方法（如果需要）
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 可以根据需要实现单元格合并逻辑
      return {
        rowspan: 1,
        colspan: 1
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.form-row:last-child {
  margin-bottom: 0;
}

.el-input {
  width: 170px;
}

:deep(.el-form-item) {
  margin-right: 15px;
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  color: #606266;
  float: none;
  line-height: 1;
  padding: 0 8px 0 0;
}

:deep(.el-form-item__content) {
  width: 180px;
  margin-left: 0 !important;
  line-height: 1;
}

:deep(.el-input),
:deep(.el-select) {
  width: 100%;
}

/* 日期选择器样式 */
:deep(.el-date-editor--daterange) {
  width: 260px !important;
}

/* 最后一个form-item（按钮组）不需要固定宽度 */
:deep(.el-form-item:last-child .el-form-item__content) {
  width: auto;
}

.search-wrapper {
  margin-bottom: 20px;
}

/* 按钮样式 */
.el-button {
  margin-left: 10px;
}

.operation-container {
  margin-top: 20px;
  margin-bottom: 20px;
}

.operation-container .el-button {
  margin-right: 10px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

/* 确保表格内容不会被截断 */
.el-table .cell {
  white-space: nowrap;
}

/* 调整按钮样式 */
.el-button--text {
  padding: 0;
  margin: 0;
}

/* 调整表格行高 */
.el-table td {
  padding: 8px 0;
}

.amount {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}
.el-input {
  width: 230px;
}
:deep(.el-dialog__body) {
  padding: 20px 40px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-input-group__append) {
  padding: 0 10px;
}

/* 滚动条样式优化 */
.dialog-content-wrapper {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background: #f5f7fa;
  }
}

/* 确保表格内容不会被截断 */
.el-table .cell {
  white-space: nowrap;
}

/* 调整按钮样式 */
.el-button--text {
  padding: 0;
  margin: 0;
}

.collapse-header {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #303133;

  .view-btn {
    color: #409eff;
    font-size: 14px;
    cursor: pointer;
  }
}

.detail-content {
  background: #fff;
  // border: 2px solid #ebeef5;
  // margin-top: 20px;

  .contract-no {
    color: #1b86ee;
    font-size: 16px;
    margin: 20px;
  }
}

.project-type {
  margin-top: 20px;
  width: 100%;
  .type-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 20px;
    padding-left: 10px;
    border-left: 4px solid #409eff;
  }

  :deep(.el-table) {
    th {
      width: 100%;
      background-color: #f5f7fa;
      color: #606266;
      padding: 8px 0;
      font-weight: normal;
    }

    td {
      padding: 8px;
      color: #606266;
    }

    &::before,
    &::after {
      background-color: #ebeef5;
    }

    .el-table__cell {
      border-color: #ebeef5;
    }
  }
}

.type-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  // margin-bottom: 20px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.contract-upload-section {
  margin: 20px 0;

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 15px;
    color: #303133;
  }

  .upload-box {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409eff;
    }
  }
}

.upload-box {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  text-align: center;
  padding: 20px;
  background-color: #fafafa;
}

.section-title {
  margin-top: 20px;
  font-size: 16px;
  font-weight: bold;
  position: relative;
  padding-left: 12px;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 18px;
  background-color: #1e6ced;
  border-radius: 2px;
}

.contract-info {
  border-radius: 4px;
  margin-top: 0; // 添加这行来覆盖可能继承的margin
  .info-item {
    display: flex;
    border-bottom: 1px solid #ebeef5;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      width: 130px;
      padding: 12px;
      background-color: #f5f7fa;
      // color: #606266;
      color: black;
      font-size: 14px;
      border-right: 1px solid #ebeef5;
    }

    .info-content {
      flex: 1;
      padding: 12px;
      min-height: 44px;
      display: flex;
      align-items: center;
      color: #606266;
      font-size: 14px;

      &:has(.download-link) {
        justify-content: space-between;
      }

      .download-link {
        color: #409eff;
        text-decoration: none;

        &:hover {
          text-decoration: underline;
        }
      }

      .button-group {
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
}

/* 正常显示时的样式 */
.project-type {
  width: 100%;

  :deep(.el-table) {
    width: 100%;

    .el-table__inner-wrapper,
    .el-table__header-wrapper,
    .el-table__body-wrapper {
      width: 100% !important;
    }
  }
}

.info-section {
  // padding: 20px;
  background: #fff;

  .info-row {
    display: flex;
    margin-bottom: 1px;

    &.full-width {
      .info-label {
        width: 180px;
        color: black;
        font-weight: bold;
      }
      .info-content {
        flex: 1;
        color: black;
      }
    }

    &.three-cols {
      .info-col {
        flex: 1;
        margin-right: 1px;
        &:last-child {
          margin-right: 0;
        }
      }
    }

    .info-col {
      display: flex;
      flex: 1;
      margin-right: 1px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .info-label {
    width: 100px;
    // padding: 12px 20px;
    padding: 12px;
    background-color: #f5f7fa;
    color: black;
    font-size: 14px;
    border: 1px solid #ebeef5;
    display: flex;
    align-items: center;
  }

  .info-content {
    padding: 12px 20px;
    min-height: 44px;
    border: 1px solid #ebeef5;
    border-left: none;
    display: flex;
    align-items: center;
    color: black;
    font-size: 14px;
    flex: 1;
  }
}

@media print {
  #printArea {
    width: 100% !important;

    .el-table {
      width: 100% !important;

      /* 表格容器样式 */
      .el-table__inner-wrapper,
      .el-table__header-wrapper,
      .el-table__body-wrapper {
        width: 100% !important;
      }

      /* 表格主体样式 */
      .el-table__header,
      .el-table__body {
        width: 100% !important;
        table-layout: fixed !important;
        border-collapse: collapse !important;
      }

      /* 单元格样式 */
      .el-table__cell {
        border: 1px solid #dcdfe6 !important;
        padding: 8px !important;
      }

      /* 表头样式 */
      .el-table__header th {
        background-color: #f5f7fa !important;
        font-weight: bold !important;
      }
    }
  }

  /* 隐藏不需要打印的元素 */
  .el-button,
  .dialog-footer {
    display: none !important;
  }
}
</style>
